﻿/**
 * jQuery twiPicZoom plugin
 * @author: feitianxinhong  http://xuzhihong1987.blog.163.com/
 * @version 1.0
 * @create date:2013-02-01
 * @copyright (c) 2013 feitianxinhong/tyingsoft/twilight  http://www.tyingsoft.com
 * @example Visit 
 */

(function ($) {
    $.fn.twiPicZoom = function (config) {
        config = $.extend({
            // sign: 'type',            //img的标识属性名，默认为type.  ->  type="twiPicZoom" 
            // signValue: 'twiPicZoom',   //img的标识属性值，默认为twiPicZoom  
            srcField:'src'   //图片路径属性
        }, config);

        // Caching the jQuery object with all elements matched
        var jQueryMatchedObj = this; // This, in this context, refer to jQuery object

        //内部参数
        var Vars = {
            beginDrag: false, //开始拖动 
            clientX: 0,  //拖动前坐标
            clientY: 0,
            pics: [],  //图片数组
            currentPicIndex: 0  //当前显示放大的图片，在图片数组中的索引
        };

        function appendHtml(src) {
            /*<div id="twiPicZoom">
            <div id="twiPicZoom_bg"></div>
            <div id="twiPicZoom_close"></div>
            <div id="twiPicZoom_content">
            <div><img alt="" src="../../samplePictures/Desert.jpg" /></div>
            </div> 
            <div id="twiPicZoom_content_top"></div>
            </div>*/
            if ($("#twiPicZoom").length != 0) {
                $("#twiPicZoom").remove();
            }
            var html = '<div id="twiPicZoom">';
            html += '<div id="twiPicZoom_bg"></div>';
            html += '<div id="twiPicZoom_close"></div>';
            html += '<div id="twiPicZoom_previous"></div>';
            html += '<div id="twiPicZoom_next"></div>';
            html += '<div id="twiPicZoom_content">';
            html += '<div><img id="twiPicZoom_main_img" alt="" src="' + src + '" /></div>';
            html += '</div>';
            html += '<div id="twiPicZoom_content_top"></div>'; //在上面加一层和twiPicZoom_content一样的，不然image拖动后不会触发mouseup事件
            html += '</div>';
            $('body').append(html);

            $("#twiPicZoom").bind('selectstart', function () {
                return false;
            });
        }

        //关闭
        function initCloseAction() {
            $('#twiPicZoom_close').unbind('click').click(function () {
                $("#twiPicZoom").remove();
            });
        }

        //居中显示
        function setInTheMiddle() {
            var img = $('#twiPicZoom_main_img');
            var imgW = parseInt(img.css('width'));
            var imgH = parseInt(img.css('height'));
            $('#twiPicZoom_content').css({
                'margin-left': -imgW / 2,
                'margin-top': -imgH / 2
            });
            $('#twiPicZoom_content_top').css({
                'margin-left': -imgW / 2,
                'margin-top': -imgH / 2,
                width: imgW,
                height: imgH
            });
        }

        //拖拽操作
        function setDD() {
            $('#twiPicZoom_content_top').mousedown(function (eventObject) {
                if (eventObject.which == 1)  //鼠标左键按下
                {
                    Vars.beginDrag = true;
                    $(this).css('cursor', 'move');
                    Vars.clientX = eventObject.clientX;
                    Vars.clientY = eventObject.clientY;
                }
            }).mousemove(function (eventObject) {
                if (Vars.beginDrag) {
                    var offsetX = eventObject.clientX - Vars.clientX;
                    var offsetY = eventObject.clientY - Vars.clientY;
                    var left = parseInt($(this).css('left'));
                    var top = parseInt($(this).css('top'));
                    $(this).css({
                        cursor: 'move',
                        left: left + offsetX,
                        top: top + offsetY
                    });
                    $('#twiPicZoom_content').css({
                        left: left + offsetX,
                        top: top + offsetY
                    });
                    Vars.clientX = eventObject.clientX;
                    Vars.clientY = eventObject.clientY;
                }
            }).mouseup(function (eventObject) {
                Vars.beginDrag = false;
                $(this).css('cursor', 'default');
            });
        }

        //滑轮事件
        function setMousewheel() {
            $('#twiPicZoom').mousewheel(function (event, delta) {
                var img = $('#twiPicZoom_main_img');
                var imgW = parseInt(img.css('width'));
                var imgH = parseInt(img.css('height'));
                var rate = parseFloat(imgH / imgW);
                delta = delta * 30;
                img.css({
                    width: imgW + delta,
                    height: imgH + rate * delta
                });

                //图片向四周缩放
                var picContent = $('#twiPicZoom_content');
                var offsetX = delta / 2;
                var offsetY = rate * delta / 2;
                var left = parseInt(picContent.css('left'));
                var top = parseInt(picContent.css('top'));
                picContent.css({
                    left: left - offsetX,
                    top: top - offsetY
                });

                $('#twiPicZoom_content_top').css({
                    left: left - offsetX,
                    top: top - offsetY,
                    width: imgW + delta,
                    height: imgH + rate * delta
                });
            });
        }

        //前一张
        function previousAction() {
            $('#twiPicZoom_previous').unbind('click').click(function () {
                if (Vars.currentPicIndex > 0) {
                    Vars.currentPicIndex--;
                    $('#twiPicZoom_main_img').attr('src', Vars.pics[Vars.currentPicIndex]);
                    $('#twiPicZoom_next').show();
                }
                if (Vars.currentPicIndex == 0) {
                    $('#twiPicZoom_previous').hide();
                }
            });
        }

        //后一张
        function nextAction() {
            $('#twiPicZoom_next').unbind('click').click(function () {
                if (Vars.currentPicIndex < Vars.pics.length - 1) {
                    Vars.currentPicIndex++;
                    $('#twiPicZoom_main_img').attr('src', Vars.pics[Vars.currentPicIndex]);
                    $('#twiPicZoom_previous').show();
                }
                if (Vars.currentPicIndex == Vars.pics.length - 1) {
                    $('#twiPicZoom_next').hide();
                }
            });
        }

        //初始化事件
        function initAction() {
            setInTheMiddle();
            initCloseAction();
            setDD();
            setMousewheel();
            previousAction();
            nextAction();
        }

        function start() {
            // This, in this context, refer to object which the user have dblclicked
            var objDblClicked = this;
            var src = $(objDblClicked).attr(config.srcField);
            Vars.currentPicIndex = 0;
            Vars.pics.length = 0;
            if (jQueryMatchedObj.length == 1) {
                Vars.pics.push($(objDblClicked).attr(config.srcField));
            }
            else {
                for (var i = 0; i < jQueryMatchedObj.length; i++) {
                    Vars.pics.push($(jQueryMatchedObj[i]).attr(config.srcField));
                }
            }
            while (Vars.pics[Vars.currentPicIndex] != src) {
                Vars.currentPicIndex++;
            }
            appendHtml(src);
            initAction();
            if (Vars.currentPicIndex == 0) {
                $('#twiPicZoom_previous').hide();
            }
            if (Vars.currentPicIndex == Vars.pics.length - 1) {
                $('#twiPicZoom_next').hide();
            }
        }

        // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
        return this.unbind('dblclick').dblclick(start);

        /*下面的方式，当页面布局比较复杂时，效率较低*/
        //        return this.each(function () {
        //            $(this).find('img[' + config.sign + '="' + config.signValue + '"]').unbind('dblclick').dblclick(function () {
        //                Vars.pics = $(jQueryMatchedObj).find('img[' + config.sign + '="' + config.signValue + '"]');
        //                var src = $(this).attr('src');
        //                Vars.currentPicIndex = 0;
        //                while ($(Vars.pics[Vars.currentPicIndex]).attr('src') != src) {
        //                    Vars.currentPicIndex++;
        //                }
        //                appendHtml(src);
        //                initAction();
        //                if (Vars.currentPicIndex == 0) {
        //                    $('#twiPicZoom_previous').hide();
        //                }
        //                if (Vars.currentPicIndex == Vars.pics.length - 1) {
        //                    $('#twiPicZoom_next').hide();
        //                }
        //            });
        //        });
    }
})(jQuery);